package com.springcloud.auth.utils;


import com.springcloud.auth.config.OauthConfig;
import com.springcloud.commom.utils.SpringContextUtils;
import com.springcloud.commom.utils.RedisUtil;
import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuer;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.common.message.types.ParameterStyle;
import org.apache.oltu.oauth2.rs.request.OAuthAccessResourceRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

public class OauthUtils {

    protected static Logger logger = LoggerFactory.getLogger(OauthUtils.class);

    public static String ACCESS_TOKEN = "accessToken";
    public static String getAccessToken() {
        String accessToken = null;
        try {
            HttpServletRequest request = SpringContextUtils.getRequest();
            OAuthAccessResourceRequest oauthRequest = new OAuthAccessResourceRequest(request,
                    ParameterStyle.HEADER);
            accessToken = oauthRequest.getAccessToken();
        } catch (Exception e) {
            e.printStackTrace();

            logger.info("OauthUtils获取accessToken失败!");
        }
        return accessToken;
    }

    public static OAuthIssuer createTokenInfo() {
        return new OAuthIssuerImpl(new MD5Generator());
    }

    public static void setSessionToken(String token, int expire) {
        HttpSession session = SpringContextUtils.getSession();
        session.setAttribute(OauthConfig.SESSION_TOKEN, token);
        // 设置存在时间,秒级别
        session.setMaxInactiveInterval(expire);
    }

    public static String getToken() {
        return SpringContextUtils.getRequest().getHeader(ACCESS_TOKEN);
    }

    //保存token到redis中
    public static void saveRedisToken(String acToken, String reToken, String token) {
        RedisUtil redisUtil = SpringContextUtils.getBean(RedisUtil.class);

        // 存入redis
        redisUtil.set(OauthConfig.AUTH_ACCESS_TOKEN + acToken, token, OauthConfig.ACCESS_TOKEN_EXPIRE);
        redisUtil.set(OauthConfig.AUTH_REFRESH_TOKEN + reToken, token,
                OauthConfig.REFRESH_TOKEN_EXPIRE);
    }

    //拿到 redis reToken
    public static String getRedisTokenByReToken(String reToken){
        RedisUtil redisUtil = SpringContextUtils.getBean(RedisUtil.class);

        String token = redisUtil.get(OauthConfig.AUTH_REFRESH_TOKEN + reToken);
        return token;
    }

    public static String getUserId(String token){
        TokenEntity tokenEntity = TokenHelper.validateToken(token);
        Map<String, String> map = tokenEntity.getPayload();

        return map.get(OauthConfig.TOKEN_USER_ID);
    }
}
